package control.control.authmanage;


import base.bean.StandardResponse;
import base.standard.auth.AuthLogic;
import base.standard.auth.NeedAuth;
import base.standard.constant.message.MessageCode;
import base.util.BeanUtil;
import base.util.ResponseUtil;
import base.validation.groups.RoleSave;
import base.validation.groups.RoleUpdate;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import control.module.bo.authmanage.RoleBo;
import control.module.po.authmanage.Role;
import control.module.vo.authmanage.RoleVO;
import control.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author cyj
 * @since 2020-10-20
 */
@RestController
@RequestMapping("/role")
@ResponseStatus(code = HttpStatus.OK)
@Slf4j
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @GetMapping("/all")
    @NeedAuth(auths = {"admin:admin:admin6", "admin:admin:admin10"})
    public StandardResponse getRoles(Page page) {
        IPage<Role> list = roleService.page(page);
        return ResponseUtil.success(BeanUtil.newInstanceAndCopyBatch(list, RoleVO.class));
    }

    @PostMapping
    public StandardResponse saveRole(@RequestBody @Validated(RoleSave.class) RoleBo userRoleBo) {
        Role role = BeanUtil.newInstanceAndCopy(userRoleBo, Role.class);
        boolean result = roleService.save(role);
        log.info("save role result:[{}]", result);
        return ResponseUtil.success(MessageCode.ROLE_SAVE, result);
    }

    @PutMapping
    public StandardResponse updateRole(@RequestBody @Validated(RoleUpdate.class) RoleBo userRoleBo) {
        Role role = BeanUtil.newInstanceAndCopy(userRoleBo, Role.class);
        boolean result = roleService.updateById(role);
        log.info("update role id:[{}] result:[{}]", role.getId(), result);
        return ResponseUtil.success(MessageCode.ROLE_UPDATE, result);
    }

    @DeleteMapping
    public StandardResponse deleteRole(@NotNull Integer id) {
        boolean result = roleService.removeById(id);
        log.info("delete role id:[{}] result:[{}]", id, result);
        return ResponseUtil.success(MessageCode.ROLE_DELETE, result);
    }

    @GetMapping
    @NeedAuth(auths = {"admin:admin:admin6", "admin:admin:admin"}, authLogic = AuthLogic.AND)
    public StandardResponse selectRole(@NotNull Integer id) {
        Role role = roleService.getById(id);
        RoleVO roleVO = BeanUtil.newInstanceAndCopy(role, RoleVO.class);
        return ResponseUtil.success(roleVO);
    }

}

